package com.vtc.session14;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.vtc.R;
import com.vtc.session13.Student;

@SuppressLint("ValidFragment")
public class StudentAddFormActivity extends DialogFragment{

	private EditText txtName,txtAddr,txtAge;
	private StudentAdapter adapter;
	private Student vo;
	
	public StudentAddFormActivity(StudentAdapter adapter){
		this.adapter = adapter;
	}
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
	
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle("Student Add Form");
		
		LayoutInflater inflat = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout layout =(LinearLayout) inflat.inflate(R.layout.studentaddform_activity, null);
		txtName = (EditText) layout.findViewById(R.id.studentaddform_txtName);
		txtAddr = (EditText) layout.findViewById(R.id.studentaddform_txtAddr);
		txtAge  = (EditText) layout.findViewById(R.id.studentaddform_txtAge);
		if(vo!=null){
			txtName.setText(vo.getName());
			txtAddr.setText(vo.getAddr());
			txtAge.setText(vo.getAge()+"");
		}
		builder.setView(layout);		
		builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				save();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		return builder.create();
	}
	public void setValue(Student st){
		this.vo = st;		
	}
	public void save(){
		String name = txtName.getText().toString();
		String addr = txtAddr.getText().toString();
		int    age  = Integer.parseInt(txtAge.getText().toString());
		Student student = new Student(name, addr, age);
		if(vo==null){ // add
		    this.adapter.add(student);
		}
		else{ // update
			student.setId(vo.getId());
			this.adapter.update(student);
		}
		dismiss();
	}
}
